package study.springboot.mvc.controller._9_easyexcel;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import study.eggs.result.Result;
import study.eggs.result.Results;
import study.springboot.mvc.service.easyexcel.EasyExcelService;
import study.springboot.mvc.service.easyexcel.ExcelExportData;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

@Slf4j
@RestController
@RequestMapping("/easyexcel")
public class EasyExcelController {

    /* M K Byte */
    private static final int FILE_MAX_SIZE = 1 * 1024 * 1024;

    @Autowired
    private EasyExcelService easyExcelService;

    @PostMapping("/import")
    public Result importExcel(@RequestParam MultipartFile file) {
        if (file == null || file.isEmpty()) {
            log.info("");
        }
        long size = file.getSize();
        log.info("file size (byte): {}", size);
        if (size > FILE_MAX_SIZE) {
            log.info("");
        }
        easyExcelService.importData(file);
        return Results.ok();
    }

    @PostMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        try {

            //response.setHeader("content-type", "application/octet-stream");
//            response.setContentType("application/octet-stream");
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //设置响应参数
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "sadf" + ".xlsx");
            //获取输出流
            OutputStream out =  response.getOutputStream();
            //
            EasyExcel.write(out, ExcelExportData.class)
                    .sheet("模板")
                    .doWrite(easyExcelService.exportData());
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
    }
}
